package com.seo.utils;

import org.apache.commons.lang3.StringUtils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.seo.pojo.ReturnBody;
import com.seo.pojo.SmsTemplet;

import lombok.extern.slf4j.Slf4j;

/**
 * 短信工具类
 * 
 * @author Administrator
 * @version 2017.12.01 11:40
 */
@Slf4j
public class SmsUtil {

	/**
	 * 发送短信
	 * 
	 * @param request request
	 * @param st      st
	 * @return String
	 */
	public static ReturnBody sendCode(SendSmsRequest request, SmsTemplet st) {
		SendSmsResponse sendSmsResponse = null;
		ReturnBody body = ReturnBody.init();
		try {
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", st.getAppKey(), st.getAppSecret());
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dysmsapi", st.getSendUrl());
			IAcsClient acsClient = new DefaultAcsClient(profile);
			request.setMethod(MethodType.POST);
			request.setSignName(st.getSign());
			request.setTemplateCode(st.getTempletId());
			sendSmsResponse = acsClient.getAcsResponse(request);
			String code = sendSmsResponse.getCode();
			log.info("发送短信返回结果[{}]", code);
			if (StringUtils.isEmpty(code)) {
				return body.error("发送失败!");
			}

			if (code.equals("OK")) {
				log.info("发送成功");
				return body.success();
			} else if (code.equals("isv.BUSINESS_LIMIT_CONTROL")) {
				log.error("[{}]-请求次数过于频繁,请1分钟后重发!", code);
				return body.error("请求次数过于频繁,请1分钟后重发!");
			} else {
				log.error("[{}]-发送失败!", code);
				return body.error("发送失败!");
			}
		} catch (ClientException e) {
			log.error("异常-[{}]", e);
			return body.error("发送失败!");
		}
	}

}
